from django.db import models
from django.contrib.auth.models import User


class PointTransaction(models.Model):
    """积分流水表 - 用户积分的所有变动记录"""
    transaction_id = models.AutoField(primary_key=True, verbose_name='流水唯一ID', db_comment='流水唯一ID')
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE, db_column='user_id', verbose_name='用户', db_comment='用户', null=True, blank=True)
    points = models.IntegerField(verbose_name='变动积分(正/负)', db_comment='变动积分(正/负)')
    action_type = models.CharField(max_length=50, verbose_name='触发行为', db_comment='触发行为')
    related_id = models.IntegerField(null=True, blank=True, verbose_name='关联业务ID', db_comment='关联业务ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='时间', db_comment='时间')

    class Meta:
        db_table = 'xiangsu_point_transactions'
        db_table_comment = '积分流水表-用户积分的所有变动记录'
        verbose_name = '积分流水记录'
        verbose_name_plural = '积分流水记录'
        ordering = ['-created_at']

    def __str__(self):
        user_id = self.user.id if self.user else '未知用户'
        return f'用户{user_id}积分变动{self.points}'


class BusinessDictionary(models.Model):
    """业务字典表 - 关联业务ID对应的业务类型定义"""
    business_id = models.AutoField(primary_key=True, verbose_name='业务唯一ID', db_comment='业务唯一ID')
    business_type = models.CharField(max_length=50, verbose_name='业务类型', db_comment='业务类型')
    description = models.CharField(max_length=255, null=True, blank=True, verbose_name='业务描述', db_comment='业务描述')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', db_comment='创建时间')

    class Meta:
        db_table = 'xiangsu_business_dictionary'
        db_table_comment = '业务字典表-关联业务ID对应的业务类型定义'
        verbose_name = '业务字典'
        verbose_name_plural = '业务字典'

    def __str__(self):
        return str(self.business_type)


class RewardItem(models.Model):
    item_id = models.AutoField(primary_key=True, verbose_name='商品唯一ID', db_comment='商品唯一ID')
    name = models.CharField(max_length=100, verbose_name='商品名称', db_comment='商品名称')
    points_cost = models.IntegerField(verbose_name='所需积分', db_comment='所需积分')
    description = models.CharField(max_length=255, null=True, blank=True, verbose_name='描述', db_comment='描述')
    stock = models.IntegerField(default=0, verbose_name='库存', db_comment='库存')

    class Meta:
        db_table = 'xiangsu_reward_items'
        db_table_comment = '积分商城商品表'
        verbose_name = '积分商品'
        verbose_name_plural = '积分商品'

    def __str__(self):
        return self.name
